#include "renderwidget.h"
#include "textrenderer.h"

#include <QtCore>
#include "Profiler.h"

void RenderWidget::initializeGL()
{
    glClearColor(0.6, 0.6, 0.6, 1.0);

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glAlphaFunc(GL_GREATER, 0.1);
    
    TextRenderer::instance().setup();
    
    Vec3f initialPosition = {0, 0, 20};
//    cameraController.getCamera().setPosition(initialPosition);
	cameraController.moveTo(initialPosition, false);
	
	if (scene)
		scene->setupForDrawing();
	
	connect(&cameraController, SIGNAL(render()), this, SLOT(updateGL()));
}

void RenderWidget::resizeGL(int w, int h)
{
    glViewport(0, 0, (GLint)w, (GLint)h);
    cameraController.getCamera().setViewSize(w, h);
    
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    cameraController.getCamera().setProjection();
    
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void RenderWidget::paintGL()
{
	Profiler profiler("RenderWidget::paintGL");

	if (scene)
		scene->draw(&cameraController);
}

void RenderWidget::keyPressEvent(QKeyEvent* event)
{
  QWidget::keyPressEvent(event);
}

void RenderWidget::mousePressEvent(QMouseEvent* event)
{
	if (!scene)
		return;
	
    QPointF pos = event->posF();
    scene->mouseDownWithRay(cameraController.getCamera().getPickRay(pos.x(), pos.y(), true), event);
    updateGL();
}

void RenderWidget::dummySearch(QString state)
{
	scene->dummySearch(state);
	updateGL();
}

void RenderWidget::clearSelectionOrSearch()
{
	scene->clearSelectionOrSearch();
	updateGL();
}
